package com.rabbitmq.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @className: CommonConfirm
 * @description: 普通确认
 * @date: 2020/5/14
 * @author: cakin
 */
@Slf4j
public class CommonConfirm {

    public static void main( String[] args ) {
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare("exchange.confirm", "direct", true, false, null);
            channel.queueDeclare("queue.confirm", true, false, false, null);
            channel.queueBind("queue.confirm", "exchange.confirm", "routingKey");
            // 启动confirm模式
            channel.confirmSelect();

            String msg = "我是普通confirm模式";
            // 发送单条消息
            channel.basicPublish("exchange.confirm", "routingKey", MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
            try {
                // 在此阻塞，等待回复，如果回复true，进入此分支
                if (channel.waitForConfirms()) {
                    // 客户端收到了Basic.Ack
                    log.info("发送成功");
                } else {
                    // 客户端收到了Basic.Nack
                    log.info("发送失败");
                    log.info("重发消息逻辑");
                }
            } catch (InterruptedException e) {
                // 被中断,抛出InterruptedException
                log.info("catch InterruptedException");
            }
            ConnectionUtils.close(channel, connection);
        } catch (IOException e) {
            // 如果RabbitMQ停止运行，代码走到这里
            log.info("catch IOException");
        } catch (TimeoutException e) {
            log.info("catch TimeoutException");
        }
    }
}
